package com.qianseit.westore.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.beautymiracle.androidclient.R;
import com.qianseit.westore.AgentApplication;
import com.qianseit.westore.BaseDoFragment;
import com.qianseit.westore.DoActivity;
import com.qianseit.westore.Run;
import com.qianseit.westore.activity.GoodsDetailFragment.AddCartTask;
import com.qianseit.westore.http.JsonRequestBean;
import com.qianseit.westore.http.JsonRequestBean.JsonRequestCallback;
import com.qianseit.westore.http.JsonTask;
import com.qianseit.westore.http.JsonTaskHandler;
import com.qianseit.westore.util.loader.VolleyImageLoader;

public class AllGoodsListFragment extends BaseDoFragment {

	private ListView mListView;
	private ArrayList<JSONObject> listGoods = new ArrayList<JSONObject>();
	private GoodsListAdapter mGoodsListAdapter;
	private VolleyImageLoader mVolleyImageLoader;

	public AllGoodsListFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActionBar.setTitle("所有商品");
		mVolleyImageLoader = ((AgentApplication) mActivity.getApplication())
				.getImageLoader();
	}

	@Override
	public void init(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_meili_goodslist, null);
		mListView = (ListView) findViewById(R.id.fragment_meili_goodslist_listview);
		mGoodsListAdapter = new GoodsListAdapter();
		mListView.setAdapter(mGoodsListAdapter);
		new JsonTask().execute(new GetGoodsList());
	}

	private class GetGoodsList implements JsonTaskHandler {

		@Override
		public void task_response(String json_str) {
			hideLoadingDialog_mt();
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONObject child = all.optJSONObject("data");
					JSONObject items = new JSONObject(child.optString("items"));
					JSONArray item = items.optJSONArray("item");
					int count = item == null ? 0 : item.length();
					for (int i = 0; i < count; i++) {
						listGoods.add(item.getJSONObject(i));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} finally {
				mGoodsListAdapter.notifyDataSetChanged();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			showCancelableLoadingDialog();
			JsonRequestBean req = new JsonRequestBean(Run.API_URL,
					"mobileapi.goods.get_all_list");
			req.addParams("son_object", "json");
			return req;
		}

	}

	private class GoodsListAdapter extends BaseAdapter implements
			View.OnClickListener {

		@Override
		public int getCount() {
			return listGoods.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return listGoods.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(mActivity).inflate(
						R.layout.item_fragment_meili_goods, null);
			}
			JSONObject obj = getItem(position);
			((TextView) convertView
					.findViewById(R.id.item_fragment_meili_goods_price))
					.setText(Run.buildString("￥", obj.optString("price")));
			((TextView) convertView
					.findViewById(R.id.item_fragment_meili_goods_name))
					.setText(obj.optString("title"));
			ImageView iconView = (ImageView) convertView
					.findViewById(R.id.item_fragment_meili_goods_img);
			try {
				JSONArray imgJson = new JSONArray(obj.optString("item_imgs"));
				JSONObject child = null;
				String imageUrl = "";
				if (imgJson != null && imgJson.length() > 0) {
					child = imgJson.getJSONObject(0);
					imageUrl = child.optString("thisuasm_url");
				}
				if (TextUtils.isEmpty(imageUrl)) {
					imageUrl = obj.optString("default_img_url");
				}
				iconView.setImageBitmap(null);
				mVolleyImageLoader.showImage(iconView, imageUrl);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			View viewBuy = convertView
					.findViewById(R.id.item_fragment_meili_goods_buy);
			viewBuy.setTag(obj);
			viewBuy.setOnClickListener(this);
			convertView.setTag(obj);
			convertView.setOnClickListener(this);
			return convertView;
		}

		@Override
		public void onClick(View v) {
			if (v.getTag() != null) {
				JSONObject obj = (JSONObject) v.getTag();
				String goodsIID = obj.optString("iid");
				if (v.getId() == R.id.item_fragment_meili_goods_buy) {
					JSONArray skus = obj.optJSONArray("skus");
					if (skus != null && skus.length() > 0) {
						goodsIID = skus.optJSONObject(0).optString("sku_id");
						JsonTaskHandler newTask = new AddCartTask(
								(DoActivity) mActivity, mAddCarCallback,
								goodsIID, 1, "is_fastbuy");
						Run.excuteJsonTask(new JsonTask(), newTask);
					}
					return;
				}
				Intent intent = AgentActivity.intentForFragment(mActivity,
						AgentActivity.FRAGMENT_GOODS_DETAIL).putExtra(
						Run.EXTRA_CLASS_ID, goodsIID);
				mActivity.startActivity(intent);
			}
		}
	}

	private JsonRequestCallback mAddCarCallback = new JsonRequestCallback() {

		@Override
		public void task_response(String jsonStr) {
			Run.excuteJsonTask(new JsonTask(), new SubmitCarTask());
		}

	};

	private class SubmitCarTask implements JsonTaskHandler {
		private String isFastBuy = "true";

		public SubmitCarTask() {
		}

		@Override
		public JsonRequestBean task_request() {
			showCancelableLoadingDialog();
			return new JsonRequestBean(Run.API_URL, "mobileapi.cart.checkout")
					.addParams("isfastbuy", isFastBuy);
		}

		@Override
		public void task_response(String json_str) {
			hideLoadingDialog_mt();

			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all) && !all.isNull("data")) {
					JSONObject data = all.optJSONObject("data");
					String coupon_lists = "";
					if (data.optJSONArray("coupon_lists") != null) {
						coupon_lists = data.optJSONArray("coupon_lists")
								.toString();
					}
					startActivity(AgentActivity
							.intentForFragment(mActivity,
									AgentActivity.FRAGMENT_SUBMIT_SHOPPING_CAR)
							.putExtra(Run.EXTRA_DATA, data.toString())
							.putExtra(Run.EXTRA_VALUE, isFastBuy)
							.putExtra(Run.EXTRA_COUPON_DATA, coupon_lists));
				}
			} catch (Exception e) {
			}
		}
	}

}
